package com.reflection.homework;

import com.user.util.MysqlConnectUtil;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DaoImpl {

    //将对象插入到对应的表中（表名与类名相同，字段名与属性名相同）
    public static void insert(Object obj){
        Connection conn = null;
        PreparedStatement ps = null;

        //把传递进来的对象用Class接收
        Class<?> objClass = obj.getClass();

        //反射获取类名，就是表名
        String tableName = objClass.getSimpleName();
        //反射获取当前类中的所有属性
        Field[] fields = objClass.getDeclaredFields();

        StringBuffer sb_field = new StringBuffer("insert into " + tableName + "(");
        StringBuffer sb_value = new StringBuffer(") values(");

        try {

            conn = MysqlConnectUtil.getConn();


            //遍历所有的属性，充当字段名
            for (Field field : fields) {
                //如果遇到私有的属性，必须设置为允许访问
                field.setAccessible(true);
                //拼接字段名
                sb_field.append(field.getName()+",");
                //拼接所有字段的具体值

                //如果当前字段是字符串类型，需要加单引号
                if (String.class.isAssignableFrom(field.getType())) {
                    sb_value.append("'"+field.get(obj)+"',");
                }else{
                    sb_value.append(field.get(obj)+",");
                }

            }

            String fieldStr = sb_field.substring(0,sb_field.lastIndexOf(","));
            String valueStr = sb_value.substring(0,sb_value.lastIndexOf(","))+")";

            System.out.println("sql:"+fieldStr+valueStr);

            ps = conn.prepareStatement(fieldStr+valueStr);

            ps.executeUpdate();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            MysqlConnectUtil.closed(conn,ps);
        }

    }

    //查询某个表中的所有记录，表名与类名相同，字段名与属性名相同
    public static <T> List<T> getList(Class<T> clazz){

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        List<T> listObj = new ArrayList<>();

        //反射获取类名，就是表名
        String tableName = clazz.getSimpleName();
        //反射获取当前类中的所有属性
        Field[] fields = clazz.getDeclaredFields();

        StringBuffer sb = new StringBuffer("select ");

        try {
            conn = MysqlConnectUtil.getConn();

            for (Field field : fields) {
                field.setAccessible(true);
                sb.append(field.getName()+",");
            }

            String sql = sb.substring(0,sb.lastIndexOf(","))+" from "+tableName;

            System.out.println("sql:"+sql);

            ps = conn.prepareStatement(sql);

            rs = ps.executeQuery();

            while(rs.next()){

                T t = clazz.newInstance();

                for (Field field : fields) {
                    field.setAccessible(true);
                    field.set(t,rs.getObject(field.getName()));
                }

                listObj.add(t);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            MysqlConnectUtil.closed(conn,ps,rs);
        }

        return listObj;
    }
    /**
     * 根据查询语句和类型名称，获得对应的对象集合；
     *
     * @param sql
     * @param clazz 集合中的类型
     * @param params
     * @return 查询结果
     */
    public static <T> List<T> query(String sql, Class<T> clazz, Object... params)  {
        return null;
    }
}
